//
//  Utils.m
//  AppManagement
//
//  Created by 珍 on 16/5/19.
//  Copyright © 2016年 abb.is.dev.eas. All rights reserved.
//

#import "Utils.h"
#import "CordovaViewController.h"
@implementation Utils


#pragma mark - document

+ (NSString *)getDocumentPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return documentsDirectory;
}

+ (BOOL)saveToDocumentWithFileName:(NSString *)fileName dict:(NSDictionary *)dict
{
    NSString *filePath = [[self getDocumentPath] stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:filePath isDirectory:nil]) {
        [fm removeItemAtPath:filePath error:nil];
    }
    
    return [dict writeToFile:filePath atomically:YES];
}

+ (NSDictionary *)readFromDocumentWithFileName:(NSString *)fileName
{
    NSString *filePath = [[self getDocumentPath] stringByAppendingPathComponent:fileName];
    
    return [[NSDictionary alloc] initWithContentsOfFile:filePath];
}

+ (BOOL)deleteFromDocumentWithFileName:(NSString *)fileName
{
    NSString *filePath = [[self getDocumentPath] stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:filePath isDirectory:nil]) {
        return [fm removeItemAtPath:filePath error:nil];
    }
    
    return YES;
}



#pragma mark - document

+ (NSString *)getCachesPath
{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    return documentsDirectory;
}

+ (BOOL)saveToCachesWithFileName:(NSString *)fileName dict:(NSDictionary *)dict
{
    NSString *filePath = [[self getCachesPath] stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:filePath isDirectory:nil]) {
        [fm removeItemAtPath:filePath error:nil];
    }
    
    return [dict writeToFile:filePath atomically:YES];
}

+ (NSDictionary *)readFromCachesWithFileName:(NSString *)fileName
{
    NSString *filePath = [[self getCachesPath] stringByAppendingPathComponent:fileName];
    
    return [[NSDictionary alloc] initWithContentsOfFile:filePath];
}

+ (BOOL)deleteFromCachesWithFileName:(NSString *)fileName
{
    NSString *filePath = [[self getCachesPath] stringByAppendingPathComponent:fileName];
    NSFileManager *fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:filePath isDirectory:nil]) {
        return [fm removeItemAtPath:filePath error:nil];
    }
    
    return YES;
}


//----------------------------

+ (void) copyFolderToPath:(NSString *)path SuccessAction:(void (^)(void))action{
    
    NSString *folderSavePath = [NSString stringWithFormat:@"%@/plugins",path];
    NSString *folderReadPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www/plugins"];
    NSString *folderSavePath1 = [NSString stringWithFormat:@"%@/cordova-js-src",path];
    NSString *folderReadPath1 = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"www/cordova-js-src"];
    
    
    NSString *cordovaReadPath = [[NSBundle mainBundle] pathForResource:@"www/cordova" ofType:@"js"];
    NSString *cordovaSavePath = [NSString stringWithFormat:@"%@/cordova.js",path];
    
    NSString *cordovaPluginsReadPath = [[NSBundle mainBundle] pathForResource:@"www/cordova_plugins" ofType:@"js"];
    NSString *cordovaPluginsSavePath = [NSString stringWithFormat:@"%@/cordova_plugins.js",path];
    
    //    NSString *cordovaJSReadPath = [[NSBundle mainBundle] pathForResource:@"www/js/plugin" ofType:@"js"];
    //    NSString *cordovaJSSavePath = [NSString stringWithFormat:@"%@/www/js/plugin.js",path];
    
    BOOL copyFolder = [self fileExistAtCopyToPath:folderSavePath copyFromPath:folderReadPath isFolder:YES];
    BOOL copyFolder1 = [self fileExistAtCopyToPath:folderSavePath1 copyFromPath:folderReadPath1 isFolder:YES];
    
    BOOL copyCordova = [self fileExistAtCopyToPath:cordovaSavePath copyFromPath:cordovaReadPath isFolder:NO];
    BOOL copyCordovaPulgin = [self fileExistAtCopyToPath:cordovaPluginsSavePath copyFromPath:cordovaPluginsReadPath isFolder:NO];
    //    BOOL copyJS = [self fileExistAtCopyToPath:cordovaJSSavePath copyFromPath:cordovaJSReadPath isFolder:NO];
    
    //    BOOL copyDB = NO;
    //    if (isUpdate) {
    //
    //        NSString *dbReadPath = [NSString stringWithFormat:@"%@/temp_db",path];
    //        NSString *dbSavePath = [NSString stringWithFormat:@"%@/www/db",path];
    //        copyDB = [self fileExistAtCopyToPath:dbSavePath copyFromPath:dbReadPath isFolder:YES];
    //        if (copyDB) {
    //
    //            NSError *error = nil;
    //            BOOL delete = [[NSFileManager defaultManager] removeItemAtPath:dbReadPath error:&error];
    //            if (delete) {
    //
    //                NSLog(@"删除 %@ 原文件成功", dbReadPath);
    //
    //            }
    //            else {
    //
    //                NSLog(@"删除 %@ 原文件失败 error:%@", dbReadPath, error);
    //            }
    //        }
    //    }
    
    if (copyFolder && copyFolder1 && copyCordova && copyCordovaPulgin /*&& copyJS*/ ) {
        
        NSLog(@"文件全部拷贝成功回调");
        //        if (isUpdate) {
        //
        //            dataPer = 1;
        //            [HUD hide:YES];
        //            if (copyDB) {
        //
        //                NSString *configOriginPath = [NSString stringWithFormat:@"%@/temp_config/config.json",path];
        //                NSData *configOriginData = [NSData dataWithContentsOfFile:configOriginPath];
        //                if (configOriginData.length != 0) {
        //
        //                    id configOriginResult = [NSJSONSerialization JSONObjectWithData:configOriginData options:0 error:nil];
        //                    NSArray *dbOriginOper = [configOriginResult objectForKey:@"dbOper"];
        //
        //                    NSString *configReadPath = [NSString stringWithFormat:@"%@/www/config/config.json",path];
        //                    NSData *configReadData = [NSData dataWithContentsOfFile:configReadPath];
        //                    if (configReadData.length != 0) {
        //
        //                        id result = [NSJSONSerialization JSONObjectWithData:configReadData options:0 error:nil];
        //                        NSArray *dbOper = [result objectForKey:@"dbOper"];
        //
        //                        if ([dbOper count] != 0) {
        //
        //                            for (int i = (int)[dbOriginOper count]; i < [dbOper count]; i ++) {
        //
        //                                NSDictionary *dict = [dbOper objectAtIndex:i];
        //                                NSString *dbName = [dict objectForKey:@"dbName"];
        //                                NSString *sql = [dict objectForKey:@"sql"];
        //
        //                                BOOL res = [[JFDataBase shareDataBaseWithDBName:dbName] executeUpdateUseSql:sql];
        //                                if (res) {
        //                                    NSLog(@"修改数据库成功");
        //                                }
        //                            }
        //                        }
        //                    }
        //                }
        //                [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"1"] callbackId:self.callbackId];
        //            }
        //            else {
        //
        //                NSDictionary *returnJson = @{@"status": @{@"code": @"-1", @"msg": @"文件全部拷贝失败回调"}};
        //                [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:returnJson] callbackId:self.callbackId];
        //            }
        //        }
        //        else {
        //
        //            dataPer = 1;
        //            [HUD hide:YES];
        //            [self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"1"] callbackId:self.callbackId];
        //        }
        

        if (action) {
            action();
        }
    }
    else {
        
        
        NSLog(@"文件全部拷贝失败");
        NSDictionary *returnJson = @{@"status": @{@"code": @"-1", @"msg": @"文件全部拷贝失败回调"}};
        NSError *error = nil;
        BOOL delete = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        if (!delete) {
            
            NSLog(@"文件夹%@删除成功",path);
        }
    }

}



+ (BOOL) fileManager:(NSFileManager *) fileManager shouldProceedAfterError:(NSError *) error copyingItemAtPath:(NSString *) srcPath toPath:(NSString *) dstPath {
    
    if ([error code] == 516) //error code for: The operation couldn’t be completed. File exists
        return YES;
    else
        return NO;
}

+ (BOOL) fileExistAtCopyToPath:(NSString *) toPath copyFromPath:(NSString *) fromPath isFolder:(BOOL) isFolder {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (isFolder) {
        
        fileManager.delegate = self;
    }
    NSString *toString = [[toPath componentsSeparatedByString:@"/"] lastObject];
    
    NSError *error = nil;
    //if exist with copy to path
    if ([fileManager fileExistsAtPath:toPath]) {
        
        BOOL delete = [fileManager removeItemAtPath:toPath error:&error];
        if (delete) {
            NSLog(@"删除toPath %@ 成功", toString);
            BOOL copy = [fileManager copyItemAtPath:fromPath toPath:toPath error:&error];
            if (copy) {
                NSLog(@"复制toPath %@ 成功", toString);
                return YES;
            }
            else {
                NSLog(@"复制toPath %@ 失败 error:%@", toString, error);
                return NO;
            }
        }
        else {
            NSLog(@"删除toPath %@ 失败 error:%@", toString, error);
            return NO;
        }
    }
    else {
        
        BOOL create = NO;
        if (isFolder) {
            
            create = [fileManager createDirectoryAtPath:toPath withIntermediateDirectories:YES attributes:nil error:&error];
        }
        else {
            
            create = YES;
        }
        if (create) {
            NSLog(@"创建toPath %@ 成功", toString);
            BOOL copy = [fileManager copyItemAtPath:fromPath toPath:toPath error:&error];
            if (copy) {
                
                NSLog(@"复制toPath %@ 成功", toString);
                return YES;
            }
            else {
                NSLog(@"复制toPath %@ 失败 error:%@", toString, error);
                return NO;
            }
        }
        else {
            NSLog(@"创建toPath %@ 失败 error:%@", toString, error);
            return NO;
        }
    }
    
}


@end
